// luofei
//
// 滑动菜单

const { ccclass, property } = cc._decorator;

@ccclass
export default class Menu_0 extends cc.Component {

    @property({ type: cc.Node, displayName: "菜单" })
    mMenu: cc.Node = null;

    @property({ type: cc.Node, displayName: "菜单内容" })
    mContent: cc.Node = null;

    _middleIndex: number = 0;
    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.initMenu();

        this.mContent.on("position-changed", this.updateContentItemScale, this);
    }

    start() {

    }

    // update (dt) {}

    onDestroy() {
        this.mContent.off("position-changed", this.updateContentItemScale, this);
    }

    // 初始化菜单
    initMenu() {
        let itemCount = this.mContent.childrenCount;
        this._middleIndex = itemCount / 2;
        for (let i = 0; i < itemCount; i++) {
            this.mContent.children[i].scale = this.getItemScale(i);
        }

        for (let i = 0; i < itemCount; i++) {
            this.mContent.children[i].position = this.getItemPos(i);
            // this.mContent.children[i].setLocalZOrder(itemCount - i);

            cc.log("index: " + i + ", x: " + this.mContent.children[i].x + ", y: " + this.mContent.children[i].y + ", scale: " + this.mContent.children[i].scale);
        }
    }

    getItemPos(index) {
        let pos = cc.v2(0, 0);
        let offsetIndex = 0;

        if (index < this._middleIndex) {
            offsetIndex = -(this._middleIndex - index);
        } else if (index > this._middleIndex) {
            offsetIndex = index - this._middleIndex;
        }

        pos = pos.add(cc.v2(offsetIndex * 300));

        let offsetX = 0;
        if (index < this._middleIndex) {
        } else if (index > this._middleIndex) {
            offsetX = this.mContent.children[index - 1].width / 2;
            cc.log(index + " : " + this.mContent.children[index - 1].name + ": " + offsetX);
        }
        // pos.x += offsetX;

        return pos;
    }

    getItemScale(index) {
        let middleScale = 1;
        let itemScale = middleScale;

        let offsetIndex = 0;

        if (index < this._middleIndex) {
            offsetIndex = this._middleIndex - index;
        } else if (index > this._middleIndex) {
            offsetIndex = index - this._middleIndex;
        }
        // itemScale = 1 - index * 0.15;
        itemScale = 1;

        return itemScale;
    }

    updateContentItemScale() {
        cc.log("x: " + this.mContent.position.x + ", y: " + this.mContent.position.y)
    }

    backToHome() {
        cc.director.loadScene("TestItemScrollView");
    }
}
